import axios, {
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosInstance,
} from "axios";
import store from "@/store";
import { ElMessage } from "element-plus";
const baseURL: any = import.meta.env.VITE_BASE_URL;

const service: AxiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 15000,
});
// 请求前的统一处理
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // JWT鉴权处理
    if (store.getters["user/token"]) {
      config.headers["Authorization"] = "Bearer " + store.state.user.token;
      config.headers["X-Authorization"] =
        "Bearer " + store.state.user.refreshToken;
    }
    return config;
  },
  (error: AxiosError) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    checkResponse(response);
    // console.log(response);
    if (response.config.responseType === "blob") {
      var filenames = response.headers["content-disposition"];
      // console.log(response);
      
      if (filenames.includes(".xls") || filenames.includes(".xlsx")) {
        acceptExport(
          response.data,
          decodeURIComponent(filenames.split(`'`)[2]),
          "application/vnd.ms-excel"
        );
      } else if (filenames.includes(".pdf")) {
        if (response.config.headers["handle"] === "preview") {
          window.open(
            window.URL.createObjectURL(
              new Blob([response.data], { type: "application/pdf" })
            )
          );
          return null;
        } else {
          acceptExport(
            response.data,
            decodeURIComponent(filenames.split(`'`)[2]),
            "application/pdf"
          );
        }
      }
      if (response.status === 200) {
        return response.data;
      } else {
        ElMessage({
          message: response.statusText || "服务异常",
          type: "error",
          duration: 3 * 1000,
        });
        return Promise.reject();
      }
    }
    const res = response.data;

    if (res.statusCode === 200) {
      return res;
    } else {
      showError(res);
      return Promise.reject(res);
    }
  },
  (error: AxiosError) => {
    const badMessage: any = error.message || error;
    const code = parseInt(
      badMessage.toString().replace("Request failed with status code ", "")
    );
    showError({ code, message: badMessage });
    return Promise.reject(error);
  }
);

function checkResponse(res: any) {
  //设置token、
  if (
    res.headers.hasOwnProperty("access-token") &&
    res.headers.hasOwnProperty("x-access-token")
  ) {
    var params = {
      token: res.headers["access-token"],
      refreshToken: res.headers["x-access-token"],
    };
    store.dispatch("user/refreshToken", params);
  }
}

// 错误处理
function showError(error: any) {
  // token过期，清除本地数据，并跳转至登录页面
  if (error.code === 401) {
    ElMessage({
      message: "登录已过期",
      type: "error",
      duration: 3 * 1000,
    });
    store.dispatch("user/loginOut");
  } else {
    ElMessage({
      message: error.errors || error.message || "服务异常",
      type: "error",
      duration: 3 * 1000,
    });
  }
}

function acceptExport(data: object, fileName: string, type: string) {
  if (!data) {
    return;
  }
  if (window.navigator.msSaveOrOpenBlob) {
    // 兼容IE
    var blob = new Blob([data], { type: type });
    navigator.msSaveBlob(blob, fileName);
  } else {
    var blob = new Blob([data], { type: type });
    var elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  }
}
export default service;
